package com.jason.www.controller;


import com.jason.www.domain.User;
import com.jason.www.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    //跳转到登录页面
    @RequestMapping(value = "/toLogin")
    public String toLogin(){
        return "login";
    }
    //实现用户登录
    @RequestMapping(value = "/login")
    public ModelAndView Login(String loginName, String loginPassword,HttpServletRequest request){
        SavedRequest savedRequest = WebUtils.getSavedRequest(request);//shiro通过WebUtils工具类保存了当前的路由地址，用户认证通过后可以返回当前地址
        ModelAndView mav=new ModelAndView();
        User user=userService.getUserByLoginName(loginName);
        if(user==null){
            mav.setViewName("login");
            mav.addObject("msg","用户不存在");
            return mav;
        }
        if(!user.getLoginPassword().equals(loginPassword)){
            mav.setViewName("login");
            mav.addObject("msg","账号密码错误");
            return mav;
        }
        SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());//如果原来有的话，就退出
        //登录后存放进shiro token
        UsernamePasswordToken token=new UsernamePasswordToken(user.getLoginName(),user.getLoginPassword());
        Subject subject= SecurityUtils.getSubject();
        subject.login(token);
        //登录成功后会跳转到successUrl配置的链接，不用管下面返回的链接
        // 获取保存的URL
        if (savedRequest == null || savedRequest.getRequestUrl() == null) {
            mav.setViewName("redirect:/success");
            return mav;
        }
        mav.setViewName("redirect:" + savedRequest.getRequestUrl());
        return mav;
    }
    //用户注销登陆
    @RequestMapping(value = "/logout")
    public String logout(){
        SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());//退出
        return "login";
    }

}
